//
//  TFChatCell.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/19.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFChatCell: UITableViewCell ,UITextViewDelegate{

    @objc public let bgView = UIView()
    @objc public let avatarImageView = UIImageView()
    @objc public var cellwidth:CGFloat = 0
    @objc public let nameAndmsgLab = UILabel()
    @objc public var model:TF_LivingChatData?
    {
        didSet{
            if(model != nil)
            {
                self.setModelUI(model: model!)
            }
        }
    }
    @objc public weak var delegate : TFChatCellDelegate?
    //yes 横屏; no 竖屏
    @objc public var isOrientationLandscape:Bool = false


    
    let content = TF_StoyCopyTextView.init()

    
    let image = UIImageView.init()
    var imageUrlView = TF_BackImagePreviewView()

 
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.bgView.backgroundColor = UIColor.white
        self.bgView.layer.cornerRadius = 14
        self.bgView.layer.masksToBounds = true
        self.contentView.addSubview(self.bgView)
        
        self.avatarImageView.layer.masksToBounds = true
        self.avatarImageView.layer.cornerRadius = 10;
        self.bgView.addSubview(self.avatarImageView)
        
        //聊天内容
        self.content.backgroundColor = UIColor.clear
        self.content.isScrollEnabled = false
        self.content.textContainer.lineFragmentPadding = 0
        self.content.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
       
        self.content.isEditable = false
        self.content.font = UIFont.PingFang(size: 14)
        

        
        self.bgView.addSubview(self.content)
        
   
        self.image.backgroundColor = UIColor.clear
        self.image.isUserInteractionEnabled = true
   
        self.bgView.addSubview(self.image)
        self.image.contentMode = .scaleAspectFill
            
        let singleRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.dealSingleTap))
        singleRecognizer.numberOfTapsRequired = 1
        self.image.addGestureRecognizer(singleRecognizer)

    }
    @objc func dealSingleTap()
    {
       
        
        let keyWindow = TalkfunSharedTools.keyWindow()
        self.imageUrlView = TF_BackImagePreviewView()
        keyWindow.addSubview(self.imageUrlView)
        
        self.imageUrlView.frame = UIScreen.main.bounds

        if ((self.model) != nil) {
            
            self.imageUrlView.layoutSubviewsUI(imageUrl: self.model!.imageURL)
           
      
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //直播聊天信息
    func setModelUI(model:TF_LivingChatData)

    {
        
        var nickNamecolor = UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1)
        var msgColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1)
       
        if (self.isOrientationLandscape) {
            self.bgView.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.8)
           
            nickNamecolor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1)
            
            msgColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
            
        } else {
            self.bgView.backgroundColor = UIColor.white
            nickNamecolor = UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1)
            
            msgColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1)
           
          
        }
        
                var  roleStr = ""
        if (model.role == .roleSpadmin) {
                    roleStr = "老师"
                }
                //=============== 如果是助教说的话 =================
        else if (model.role == .roleAdmin)
                {
                    roleStr = "助教"

                }
        self.avatarImageView.layer.cornerRadius = 10
        
        self.avatarImageView.sd_setImage(with: NSURL.init(string: model.avatar) as URL?, placeholderImage: UIImage.init(named: "HTLive.bundle/占位图"))
     
        let model_imageURL = model.imageURL as NSString
        if (model_imageURL.length>0) {
            model.msg = ""
        } else {
            model.msg = model.msg
        }
        let nickname = model.nickname + " "
        let  str =  nickname + model.msg
        
        let contentDict = TalkfunSharedTools.assembleAttributeString(str, boundingSize: CGSize(width: self.cellwidth-35-16-12-16, height: CGFloat.greatestFiniteMagnitude), fontSize: 14, shadow: false) as NSDictionary

        let attr = contentDict["attributeStr"] as! NSAttributedString

        
        let AttributedString = NSMutableAttributedString.init(attributedString: attr)

        
        let attr35: [NSAttributedString.Key : Any] = [.font: UIFont.PingFang(size: 14) as Any,.foregroundColor: msgColor,]
        AttributedString.addAttributes(attr35, range: NSRange(location: 0, length: attr.length))
      
        
        //名字的颜色
        let attr36: [NSAttributedString.Key : Any] = [.font: UIFont.PingFang(size: 14) as Any,.foregroundColor: nickNamecolor,]
        
        AttributedString.addAttributes(attr36, range: NSRange(location: 0, length: (model.nickname as NSString).length))

        //助教或者老师
        if (roleStr.count > 0) {
              let attch = NSTextAttachment()
            if (model.role == .roleSpadmin) {
                attch.image = UIImage.init(named: "HTLive.bundle/chat_tag_teacher")
            } else {
                attch.image = UIImage.init(named: "HTLive.bundle/chat_tag_assistant")
               
            }
            
            attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)
            let imageStr = NSAttributedString.init(attachment: attch)
            
            
            let nickname_length = (model.nickname as NSString).length
            //插入老师标签
            AttributedString.insert(imageStr, at: nickname_length)
            
            
            let newStr = NSAttributedString.init(string: " ")
             //插入" "
             AttributedString.insert(newStr, at: nickname_length)
            
          
        }
        
        
        
        let size = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:self.cellwidth-35-16-12-16, labelfont: UIFont.PingFang(size: 14))
        
        if (model_imageURL.length>0) {  //发送图片
            var imageHight:CGFloat = 96
            var imageWidth:CGFloat = 96
            var bgY:CGFloat = 0
            if (self.isOrientationLandscape) {
                imageHight = 68
                imageWidth = 68
                bgY = 4
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
           
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
            } else {
                imageHight = 96;
                imageWidth = 96;
                bgY = 8;
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
             
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
            }
            if ( (model.image.size.width == model.image.size.height)) {
                
                self.image.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: self.content.frame.maxY+6, width: imageWidth, height: imageHight)
            } else if ( (model.image.size.width > model.image.size.height)) {
                let proportion:CGFloat = model.image.size.width / imageWidth;
                imageHight = model.image.size.height / proportion;
                self.image.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: self.content.frame.maxY+6, width: imageWidth, height: imageHight)
            } else if ( (model.image.size.width < model.image.size.height)) {
                let proportion:CGFloat = model.image.size.height / imageHight
                let imagew:CGFloat = model.image.size.width / proportion
                self.image.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: self.content.frame.maxY+6, width: imagew, height: imageHight)
            }
            
            self.image.image = model.image;
            if (size.width > self.image.frame.size.width) {
                self.bgView.frame = CGRect(x: 12, y: bgY, width: 34+size.width+8, height: self.image.frame.maxY+8)
            
            } else {
                self.bgView.frame = CGRect(x: 12, y: bgY, width: self.image.frame.maxX+8, height: self.image.frame.maxY+8)
                
            }
            
        } else {
            self.image.image = nil;
            self.image.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
          
            if (self.isOrientationLandscape) {
                self.bgView.frame = CGRect(x: 12, y: 4, width: size.width+16+35, height: size.height+12)
             
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
               
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
                
            } else {
                self.bgView.frame = CGRect(x: 12, y: 8, width: size.width+16+35, height: size.height+12)
               
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
             
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
            }
        }
       
        self.content.addHyperlink(font: UIFont.PingFang(size: 14), attributedText: AttributedString)
        self.content.attributedText = AttributedString;
      
    }
   
}
@objc protocol TFChatCellDelegate : NSObjectProtocol {
    //聊天链接
    func urlClick(url: NSString)
    
}
